package com.lmt.config.shiro;

import com.lmt.entity.SysPermission;
import com.lmt.entity.SysRole;
import com.lmt.entity.UserInfo;
import com.lmt.service.UserInfoService;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author MT-Lin
 */
@Log4j2
@Component
public class ShiroRealm extends AuthorizingRealm {

    private final UserInfoService userInfoService;

    @Autowired
    public ShiroRealm(UserInfoService userInfoService) {
        this.userInfoService = userInfoService;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("权限配置：ShiroRealm.doGetAuthorizationInfo()");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        UserInfo userInfo  = (UserInfo)principalCollection.getPrimaryPrincipal();
        for(SysRole sysRole:userInfo.getRoleList()){
            authorizationInfo.addRole(sysRole.getRole());
            for(SysPermission sysPermission:sysRole.getPermissions()){
                authorizationInfo.addStringPermission(sysPermission.getPermission());
            }
        }
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("登陆认证：ShiroRealm.doGetAuthenticationInfo()");
        //获取用户的输入的账号.
        String username = (String) authenticationToken.getPrincipal();
        //通过username从数据库中查找 User对象
        //实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
        UserInfo userInfo = userInfoService.findByUsername(username);
        log.info("登陆人：{}", userInfo);
        if (userInfo == null) {
            return null;
        }
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                // 用户名
                userInfo,
                //密码
                userInfo.getPassword(),
                // Realm name
                getName()
        );
        simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(userInfo.getSalt()));
        return simpleAuthenticationInfo;
    }
}
